package top.yrlby.filter;

import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.AntPathMatcher;
import top.yrlby.common.BaseContext;
import top.yrlby.common.R;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author BaiYang
 * @time 2022/9/5
 */
@WebFilter(filterName = "loginCheckFilter",urlPatterns = "/*")
@Slf4j //lombok
public class LoginCheckFilter implements Filter {

    public static final AntPathMatcher PATH_MATCHER = new AntPathMatcher();

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        String requestURI = request.getRequestURI();//拦截请求的路径
        log.info("拦截到请求：{}",requestURI);
        String[] urls = new String[]{//配置静态方行的页面
                "/employee/login",
                "/employee/logout",
                "/backend/**",
                "/front/**",
                "/common/**",
                "/user/sendMsg",
                "/user/login"
        };
        //调用check方法返回的是一个boolean类型
        boolean check = check(urls, requestURI);//判断拦截请求的路径是否为静态放行的页面

        if(check){//check方法判断为true则说明是静态放行的页面则直接放行
            log.info("本次请求{}不需要登录就能访问，直接放行",requestURI);
            filterChain.doFilter(request,response);
            return;
        }
        if(request.getSession().getAttribute("employee") != null){//判断是否登录
            log.info("用户已登录，用户id为：{}",request.getSession().getAttribute("employee"));
            filterChain.doFilter(request,response);//登录则进入直接放行
            return;
        }

        if(request.getSession().getAttribute("user") != null){
            log.info("用户已登录，用户id为：{}",request.getSession().getAttribute("user"));

            Long userId = (Long) request.getSession().getAttribute("user");
            BaseContext.setCurrentId(userId);

            filterChain.doFilter(request,response);//登录则进入直接放行
            return;
        }
        //未登录并且不是静态放行页面则到此步骤向下执行
        log.info("用户未登录");
        //5、如果未登录则返回未登录结果，通过输出流方式向客户端页面响应数据
        response.getWriter().write(JSON.toJSONString(R.error("NOTLOGIN")));//因为是void方法则需要sponse返回前台json数据
        return;
    }

    /**
     * 路径匹配，检查本次请求是否需要放行
     * @param urls: 不登录就能访问的URI列表
     * @param requestURI：用户请求的URI
     * @return
     */
    public boolean check(String[] urls, String requestURI){
        for (String urlPattern : urls) {
            //requestURI = /backend/page/login/login.html
            //urlPattern = /backend/**
            boolean match = PATH_MATCHER.match(urlPattern, requestURI);//是否和**匹配的静态放行页面
            //如果match=true，说明不登录就能访问
            if(match) {
                return true;
            }
        }
        return false; // -> /employee/page
    }
}
